package database

import (
	leaderboard "chess/config/ranklist"
	log2 "chess/log"
	"chess/pkg"
	"chess/tools"
	"context"
	"flag"
	"fmt"
	"github.com/go-redis/redis/v8"
	"google.golang.org/grpc"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strconv"
)

type GameScores struct {
	Id               int
	PlaygroundNumber int
	NickName         string
	Wins             int
	Odds             float64
}

var (
	RankAddr = flag.String("RankAddr", "rankinglist:16013", "the address to connect to")
)
var conn, err = grpc.Dial(*RankAddr, grpc.WithInsecure())
var c = leaderboard.NewProdScoreBoardServiceClient(conn)

func WinGame(ctx context.Context, roomId int, winnerId int, loserId int, nickName string, message []string) error {
	mysqlPath := tools.GetEnv("MYSQL_PATH", "localhost:3306")
	mysqlUser := tools.GetEnv("MYSQL_USER", "root")
	mysqlPassword := tools.GetEnv("MYSQL_PASSWORD", "123456")
	db, err := gorm.Open(mysql.Open(mysqlUser+":"+mysqlPassword+"@tcp("+mysqlPath+")/gamedata?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "WinGame", strconv.Itoa(roomId), "Error", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return err
	}
	playerA := GameScores{}
	err = db.AutoMigrate(&GameScores{})
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "WinGame", strconv.Itoa(roomId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return err
	}
	db.Model(GameScores{}).Where("id=?", winnerId).First(&playerA)
	if playerA.Id == 0 {
		tmpPlayer := playerA

		tmpPlayer.Id = winnerId
		tmpPlayer.NickName = nickName
		tmpPlayer.Wins += 1
		tmpPlayer.PlaygroundNumber += 1
		if winnerId == 999 {
			tmpPlayer.NickName = "AlphaGo"
		}
		tmpPlayer.Odds = float64(tmpPlayer.Wins) / float64(tmpPlayer.PlaygroundNumber)
		db.Model(GameScores{}).Create(&tmpPlayer)
	}
	if playerA.Id != 0 {
		playerA.Id = winnerId
		playerA.NickName = nickName
		if winnerId == 999 {
			playerA.NickName = "AlphaGo"
		}
		playerA.Wins += 1
		playerA.PlaygroundNumber += 1
		playerA.Odds = float64(playerA.Wins) / float64(playerA.PlaygroundNumber)
		db.Model(GameScores{}).Where("id=?", winnerId).Updates(&playerA)
	}
	playerB := GameScores{}
	db.Model(GameScores{}).Where("id=?", loserId).First(&playerB)
	if playerB.Id == 0 {
		tmpPlayer := playerB
		tmpPlayer.Id = loserId
		tmpPlayer.PlaygroundNumber += 1
		if loserId == 999 {

			playerB.NickName = "AlphaGo"
		}
		tmpPlayer.Odds = float64(tmpPlayer.Wins) / float64(tmpPlayer.PlaygroundNumber)
		db.Model(GameScores{}).Create(&tmpPlayer)
	}
	if playerB.Id != 0 {
		playerB.Id = loserId
		playerB.PlaygroundNumber += 1
		if loserId == 999 {

			playerB.NickName = "AlphaGo"
		}
		//playerB.NickName = nickName
		playerB.Odds = float64(playerB.Wins) / float64(playerB.PlaygroundNumber)
		db.Model(GameScores{}).Where("id=?", loserId).Updates(&playerB)
	}
	_, err = c.StartDataMigration(ctx, &leaderboard.StartDataMigrationRequest{UserId: int32(winnerId)})
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "WinGame", "roomid:"+strconv.Itoa(roomId)+" userid:"+strconv.Itoa(winnerId), "Error", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}

		return err
	}

	redisPath := tools.GetEnv("REDIS_PATH", "localhost:6379")
	redisPD := tools.GetEnv("REDIS_PASSWORD", "")
	rdb := redis.NewClient(&redis.Options{
		Addr:     redisPath,
		Password: redisPD, // no password set
		DB:       1,       // use default DB
		//PoolSize: 500, // 连接池大小
	})
	_, err = rdb.Del(ctx, strconv.Itoa(roomId)).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "WinGame", strconv.Itoa(roomId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return err
	}
	rdb2 := redis.NewClient(&redis.Options{
		Addr:     redisPath,
		Password: redisPD, // no password set
		DB:       5,       // use default DB
		//PoolSize: 500, // 连接池大小
	})
	message[len(message)-1] = message[len(message)-1] + "winner: " + strconv.Itoa(winnerId)
	_, err = rdb2.SAdd(ctx, strconv.Itoa(roomId), message).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "WinGame", strconv.Itoa(roomId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return err
	}
	_, ok := pkg.BoardMap[roomId]
	if ok {
		delete(pkg.BoardMap, roomId)
		writeLog, err2 := log2.WriteLog(context.Background(), "chessgame", "WinGame", strconv.Itoa(roomId), "Debug", "Remove the board")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
	}
	return err
}
